/*

 * Copyright (C) 2021 Huawei Device Co., Ltd.

 * Licensed under the Apache License, Version 2.0 (the "License");

 * you may not use this file except in compliance with the License.

 * You may obtain a copy of the License at

 *

 *     http://www.apache.org/licenses/LICENSE-2.0

 *

 * Unless required by applicable law or agreed to in writing, software

 * distributed under the License is distributed on an "AS IS" BASIS,

 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

 * See the License for the specific language governing permissions and

 * limitations under the License.

 */
package me.aartikov.alligator.helpers;

import me.aartikov.alligator.Screen;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class FractionCache {
    private Map<Screen, MiFraction> mFragmentMap;
    private FractionCache() {
        mFragmentMap = new HashMap<>();
    }

    private static volatile FractionCache instance;

    /**
     * 获取单例
     * @return MiFractionCache
     */
    public static FractionCache getInstance() {
        FractionCache localResource = instance;
        if (localResource == null) {
            synchronized (FractionCache.class) {
                localResource = instance;
                if (instance == null) {
                    localResource=  instance = new FractionCache();
                }
            }
        }
        return localResource;
    }

    /**
     * 缓存Fraction
     * @param screen Fraction对应得 screen
     * @param fraction 需要缓存的fraction
     */
    public void put(Screen screen, MiFraction fraction) {
         if (mFragmentMap == null) {
            getInstance();
        }
        mFragmentMap.put(screen, fraction);
    }

    /**
     * 获取所有fraction 缓存
     * @return Map<Screen, MiFraction>
     */
    public Map<Screen, MiFraction> getFragmentCache() {
        if (mFragmentMap == null) {
            getInstance();
        }
        return mFragmentMap;
    }

    /**
     * 从缓存中读取fraction
     * @param screen fraction绑定改的screen
     * @return MiFraction
     */
    public MiFraction get(Screen screen) {
        if (mFragmentMap == null) {
            getInstance();
        }
        return mFragmentMap.get(screen);
    }


    /**
     * 从缓存中清除fraction
     * @param currentFragment 需要清除的fraction
     */
    public void removeFragment(MiFraction currentFragment) {
        for (Iterator iterator = mFragmentMap.entrySet().iterator(); iterator.hasNext(); ) {
            Map.Entry entry = (Map.Entry) iterator.next();
            MiFraction i = (MiFraction) entry.getValue();
            if (i == currentFragment) {
                //就是调用 iterator.remove()方法可以移除掉map中键值对
                iterator.remove();
            }
        }
    }

    /**
     * 清除缓存
     */
    public void clear() {
        mFragmentMap.clear();
    }
}
